package com.starmark.gateway.springcloud.provider.proxy.dto;

import lombok.Data;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;

/**
 * 网关接口请求
 * @author starmark
 * @since 2020/8/18 001820:17
 **/
@Data
public class GatewayInterfaceRequest {


    public GatewayInterfaceRequest(ServerHttpRequest serverHttpRequest){
        this.queryParams=serverHttpRequest.getQueryParams();
        this.methodType=serverHttpRequest.getMethodValue();
       this.cookies= serverHttpRequest.getCookies();
       this.headers=serverHttpRequest.getHeaders();
    }
    /**
     * 请求token
     */
    private String accessToken;


    /**
     * 请求文件流
     */
    private String playRoad;

    /**
     * 请求参数
     */
    private  MultiValueMap<String, String> queryParams;

    /**
     * 请求方法
     */
    private String methodType;

    /**
     * cookies
     */
    private   MultiValueMap<String, HttpCookie> cookies;

    /**
     * 请求参数
     */
    private HttpHeaders headers;

    /**
     * 获取请求体中的字符串内容
     * @param serverHttpRequest
     * @return
     */
    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){

        //获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        StringBuilder sb = new StringBuilder();

        body.subscribe(buffer -> {
            byte[] bytes = new byte[buffer.readableByteCount()];
            buffer.read(bytes);
            DataBufferUtils.release(buffer);
            String bodyString = new String(bytes, StandardCharsets.UTF_8);
            sb.append(bodyString);
        });
        return sb.toString();

    }
}
